package net.lzzy.spingsecurity.service;

import net.lzzy.spingsecurity.entity.User;
import net.lzzy.spingsecurity.repository.RoleRepository;
import net.lzzy.spingsecurity.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
public class UserService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Autowired
        RoleRepository roleRepository;
@Override
public UserDetails loadUserByUsername(String s)throws
        UsernameNotFoundException {
        User user=userRepository.findByUsername(s);
        if(user==null){
        throw new UsernameNotFoundException("用户不存在");
        }
        return user;
        }
        public boolean register(String email, String username, String password){
                if (userRepository.findByUsername(username) != null) {
                        return false;
                }
                else if (userRepository.findByEmail(email) != null){
                        return false;
                }
                else {
                        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                        User user = new User();
                        user.setUsername(username);
                        user.setPassword(encoder.encode(password));
                        user.setRoles(Arrays.asList(roleRepository.findById(2).get()));
                        user.setDate(new Date());
                        userRepository.save(user);
                        return true;
                }
        }

        }